<template>
  <div class="common-layout">
    <el-row :gutter="20">
      <el-col :lg="3"></el-col>
      <el-col :lg="18">
        <el-form class="header" :model="queryParam" ref="queryRef" :inline="true">
          <el-form-item label="书名" prop="ipaddr">
            <el-select style="width: 100px" clearable v-model="queryParam.book" placeholder="书名">
              <el-option v-for="item in 7" :key="item" :label="`${('book')}${item}`" :value="`${('book')}${item}`"/>
            </el-select>
          </el-form-item>

          <el-form-item label="单元名称" prop="ipaddr">
            <el-select style="width: 100px" clearable v-model="queryParam.unit" placeholder="单元名称">
              <el-option v-for="item in 6" :key="item" :label="`${('unit')}${item}`" :value="`${('unit')}${item}`"/>
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="searchByUnit">查询</el-button>
            <el-button @click="handleQuery">重新加载</el-button>
            <el-button style="background-color: #421f7d;color: white" @click="restartArrange">随机排列</el-button>
            <el-button type="warning" @click="showBeginPrompt">{{ beginPromptText }}</el-button>
            <el-button type="success" @click="submitRecordStudy">提交记录</el-button>
          </el-form-item>
          <el-form-item style="margin-left: auto;">

            <div class="time-display">
              {{ formattedTime }}
            </div>

            <div style="white-space: nowrap;display: flex">
              <el-button
                  class="div-child"
                  plain
                  type="primary"
                  :disabled="isRunning || (isCountdown && initialTime === 0 && currentTime === 0)"
                  @click="startTimer"
              >
                {{
                  isCountdown && currentTime === 0 && initialTime > 0 && !isRunning ? '开始' : (isRunning ? '运行中' : '启动')
                }}
              </el-button>

              <el-button
                  plain
                  class="div-child"
                  type="warning"
                  :disabled="!isRunning"
                  @click="pauseTimer"
              >
                暂停
              </el-button>

              <el-button
                  plain
                  class="div-child"
                  :disabled="isRunning"
                  @click="resetTimer"
              >
                重置
              </el-button>
            </div>
          </el-form-item>
        </el-form>
      </el-col>
    </el-row>
    <el-row :gutter="20">
      <el-col :sm="24" :lg="3"></el-col>
      <el-col :sm="24" :lg="18" style="padding-right: 40px">
        <el-table
            v-loading="loading"
            :data="pageData"
            :default-sort="{ prop: 'updateTime', order: 'descending' }"
            border
            stripe
            highlight-current-row
        >
          <el-table-column v-if="false" type="selection" width="40" align="center"/>
          <el-table-column label="编号" v-if="false" width="210" prop="_id"/>
          <el-table-column label="书名" width="70" align="center" prop="book">
            <template #default="scope">
              <span v-if="scope.row.isValid === null"
                    :class="{ 'dynamic-line-through': scope.row.book }">
                {{ scope.row.book }}</span>
              <span v-if="scope.row.isValid === true"
                    :class="{ 'dynamic-line-complete': scope.row.book }">
                {{ scope.row.book }}</span>
              <span v-if="scope.row.isValid === false"
                    :class="{ 'dynamic-line-complete-outdated': scope.row.book }">
                {{ scope.row.book }}
              </span>
            </template>
          </el-table-column>
          <el-table-column label="课程" width="70" align="center" prop="unit">
            <template #default="scope">
              <span v-if="scope.row.isValid === null"
                    :class="{ 'dynamic-line-through': scope.row.unit }">
                {{ scope.row.unit }}</span>
              <span v-if="scope.row.isValid === true"
                    :class="{ 'dynamic-line-complete': scope.row.unit }">
                {{ scope.row.unit }}</span>
              <span v-if="scope.row.isValid === false"
                    :class="{ 'dynamic-line-complete-outdated': scope.row.unit }">
                {{ scope.row.unit }}
              </span>
            </template>
          </el-table-column>

          <el-table-column label="中文名" align="center" prop="chinese">
            <template #default="scope">
              <span v-if="scope.row.isValid === null"
                    :class="{ 'dynamic-line-through': scope.row.chinese }">
                {{ scope.row.chinese }}</span>
              <span v-if="scope.row.isValid === true"
                    :class="{ 'dynamic-line-complete': scope.row.chinese }">
                {{ scope.row.chinese }}</span>
              <span v-if="scope.row.isValid === false"
                    :class="{ 'dynamic-line-complete-outdated': scope.row.chinese }">
                {{ scope.row.chinese }}
              </span>
            </template>
          </el-table-column>
          <el-table-column label="词性" width="90" align="center" prop="type">
            <template #default="scope">
              <span v-if="scope.row.isValid === null"
                    :class="{ 'dynamic-line-through': scope.row.type }">
                {{ scope.row.type }}</span>
              <span v-if="scope.row.isValid === true"
                    :class="{ 'dynamic-line-complete': scope.row.type }">
                {{ scope.row.type }}</span>
              <span v-if="scope.row.isValid === false"
                    :class="{ 'dynamic-line-complete-outdated': scope.row.type }">
                {{ scope.row.type }}
              </span>
            </template>
          </el-table-column>
          <el-table-column width="100" v-if="beginPrompt === true" label="前两个字母" align="center" prop="name">
            <template #default="scope">
              {{ scope.row.name.toString().substring(0, 2) }}
            </template>
          </el-table-column>
          <el-table-column label="拼写" align="center" prop="nameAgain">
            <template #default="scope">
              <el-input @keyup.enter="handleEnter(scope.row)"
                        clearable
                        :data-row="scope.row.row_index"
                        :class="{'input-valid': scope.row.isValid, 'input-invalid': !scope.row.isValid}"
                        @blur="handleBlur(scope.row)" v-model="scope.row.nameAgain"
                        placeholder="请拼写('回车键'跳转到下一行)"></el-input>
            </template>
          </el-table-column>
          <el-table-column label="操作" align="center" width="80" class-name="small-padding fixed-width">
            <template #default="scope">
              <el-button link @click="handleColumnAudio(scope.row)" type="success">发音</el-button>
            </template>
          </el-table-column>

        </el-table>
      </el-col>
    </el-row>

    <el-backtop class="custom-backtop" :bottom="100">
      <div
          style="
        height: 100%;
        width: 100%;
        background-color: var(--el-bg-color-overlay);
        box-shadow: var(--el-box-shadow-lighter);
        text-align: center;
        line-height: 40px;
        color: #1989fa;
      "
      >
        {{ lastNum }} / {{ total }}
      </div>
    </el-backtop>
  </div>
</template>

<script setup>
// 查询
import {
  getPageUnit,
  handleColumnAudio,
  listTestPage,
  putChinToEngData,
  putStudyData,
  removeTest
} from "@/api/word/index.js";
import {getCurrentInstance, ref} from 'vue';
import {parseTime} from "@/utils/ruoyi.js";
import {useTimerStore} from "@/store/timer.js";
import {shuffleArray} from "@/api/utils/index.js";
import {addStudy_record} from "@/api/word/wordRecord.js";

let beginPrompt = ref(false);
let recordDataCorrect = ref([]); //记录正确的输入数组
let total = ref(0)
let recordFrom = ref({})
let lastNum = ref(0)
let beginPromptText = ref('显示提示');
let queryParam = ref({
  unit: '',
  book: ''
})

const showBeginPrompt = () => {
  beginPrompt.value ? beginPromptText.value = '显示提示' : beginPromptText.value = '隐藏提示'
  beginPrompt.value = !beginPrompt.value
}

const {proxy} = getCurrentInstance()
const {word_study_status} = proxy.useDict("word_study_status")
let practiceId = ref(null)

//时间
const timerStore = useTimerStore();
// 从 store 中解构 actions
timerStore.isCountdown = false;
timerStore.initialTime = 360
const {startTimer, pauseTimer, resetTimer, setInitialTime} = timerStore;
// 从 store 中解构 state 和 getters (保持响应性)
const {formattedTime, isRunning, isCountdown, initialTime, currentTime} = storeToRefs(timerStore); // 添加 currentTime

let pageData = ref([])
let loading = false

initPage()

const restartArrange = () => {
  pageData.value = shuffleArray(pageData.value)
}

function handleQuery() {
  // console.log(queryParam.value)
  resetTimer()
  getPageUnit(queryParam.value).then((res) => {
    pageData.value = []
    if (res.code === 200 && res.data !== undefined) {
      pageData.value = shuffleArray(res.data)
      total.value = res.data.length
      practiceId.value = Math.random().toString().substring(2)

      let row_index = 0
      pageData.value.forEach(item => {
        item.isValid = null
        item.row_index = row_index ++
      })
      // console.log(res)
    }
  })
}

function initPage() {
  queryParam.value.unit = 'unit' + Math.ceil(Math.random() * 5)
  queryParam.value.book = 'book' + Math.ceil(Math.random() * 6)
  handleQuery()
  practiceId.value = Math.random().toString().substring(2)
  lastNum.value = 0
  recordDataCorrect.value = []
  // console.log('follow in one’s footsteps'.replace(/[^a-zA-Z0-9\u4e00-\u9fa5]/g, "") === 'follow in one\'s footsteps'.replace(/[^a-zA-Z0-9\u4e00-\u9fa5]/g, ""))
  // queryParam.value.unit = undefined
}

function handleBlur(row) {
  // console.log(row)
  row.practiceId = practiceId.value
  if (row.nameAgain === undefined || row.nameAgain === '' || row.nameAgain.length === 0) {
    return
  }
  startTimer()
  //替换所有的字符为空
  if (row.name.toString().trim().toLowerCase().replace(/[^a-zA-Z0-9\u4e00-\u9fa5]/g, "") !==
      row.nameAgain.trim().toLowerCase().replace(/[^a-zA-Z0-9\u4e00-\u9fa5]/g, "")) {
    proxy.$modal.msgWarning("拼写错误,请再试一次")
    row.result = false
    row.isValid = false
    putChinToEngData(row)
    setTimeout(() => {
      row.nameAgain = ''
    }, 2000)
  } else {
    proxy.$modal.msgSuccess("拼写正确!")
    row.isValid = true
    row.result = true
    //避免重复添加
    if (recordDataCorrect.value.indexOf(row.name) === -1) {
      recordDataCorrect.value.push(row.name)
      lastNum.value ++
      putChinToEngData(row)
    }
  }
}

// 处理回车键事件
const handleEnter = (e) => {
  // 获取当前单元格的行索引和列索引
  // console.log(e)
  const currentRow = e.row_index;

  // 计算下一行索引（当前行 +1）
  const nextRow = currentRow + 1;

  // 检查下一行是否存在
  if (nextRow < pageData.value.length) {
    // 等待DOM更新后定位到下一行同列单元格
    nextTick(() => {
      // 选择器：行索引为nextRow，列索引为currentCol的input
      const nextInput = document.querySelector(
          // `input[data-row="${nextRow}"][data-col="${currentCol}"]`
          `input[data-row="${nextRow}"]`
      );

      // 如果找到目标单元格，使其聚焦
      if (nextInput) {
        nextInput.focus();
        //nextInput.select(); // 可选：选中内容便于编辑
      }
    });
  }
};

function searchByUnit() {
  if (queryParam.value.unit === undefined || queryParam.value.book === undefined) {
    return
  }
  proxy.$modal.msg("查询的书名:" + queryParam.value.book + "  课程名称:" + queryParam.value.unit)
  handleQuery()
}


function submitRecordStudy() {
  if (lastNum.value === 0){
    proxy.$modal.msgWarning("拼写的记录为空")
    return
  }
  if (lastNum.value !== total.value) {
    proxy.$modal.msgWarning("还有未学习的练习")
  }

  proxy.$modal.confirm('是否确认提交').then(function () {
    pauseTimer() //完成学习时，停止计时器

    recordFrom.value.book = queryParam.value.book
    recordFrom.value.unit = queryParam.value.unit
    recordFrom.value.wordNum = total.value
    recordFrom.value.practice = practiceId.value
    recordFrom.value.usedTime = formattedTime.value
    recordFrom.value.correctNum = lastNum.value
    recordFrom.value.correctRate = lastNum.value / total.value
    // console.log(recordFrom.value)
    handleInsertRecordData(recordFrom.value)
  }).catch(() => {
    proxy.$modal.msg("取消提交")
  })
}

//连接MYSQL数据库-插入数据
function handleInsertRecordData(data) {
  data.type = 'write'
  addStudy_record(data).then(res => {
    // console.log(res)
    recordFrom.value = {}
    if (res.code === 200) {
      lastNum.value = 0
      recordFrom.value = {}
      practiceId.value = Math.random().toString().substring(2)
      proxy.$modal.msgSuccess("提交成功")
    }
  })
}

</script>

<style scoped lang="scss">
.header {
  margin-top: 20px;
  display: flex;
  flex-wrap: wrap;
  margin-right: 0;
}

/* 基础样式 */
.input-base .el-input__inner {
  transition: all 0.2s ease;
  border-width: 1.5px;
}

/* 有效状态 */
.input-valid .el-input__inner {
  border-color: #00b42a;
  box-shadow: 0 0 0 2px rgba(0, 180, 42, 0.2);
}

/* 无效状态 */
.input-invalid .el-input__inner {
  border-color: #f53f3f;
}

/* 自定义大小的回到顶部按钮 */
:deep(.custom-backtop) {
  /* 自定义大小 */
  width: 100px;
  height: 40px;

  /* 其他样式调整 */
  line-height: 60px;
  border-radius: 8px;
  background-color: #67c23a;
  color: white;
  text-align: center;
  font-size: 22px;

  /* 悬停效果 */
  transition: all 0.3s;
}

:deep(.custom-backtop):hover {
  background-color: #52c41a;
  transform: scale(1.05);
}

.div-child {
  display: inline-block;
  //margin-top: -10px;
}

.col-relative {
  position: relative; /* 作为定位参考 */
}

.right-absolute {
  position: absolute;
  right: 0; /* 靠右 */
  top: 50%; /* 垂直居中（可选） */
  transform: translateY(-50%); /* 垂直居中微调 */
}

.time-display {
  font-size: 1.5rem;
  font-weight: bold;
  color: #323233;
  border: none;
  border-radius: 12px;
  background-color: #ffffff;
  min-width: 120px;
  letter-spacing: 3px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.08);
}

/* 默认状态 */
.dynamic-line-through {
  color: #5a5e66;
}

/* 拼写正确 */
.dynamic-line-complete {
  color: green;
}

/* 拼写错误 */
.dynamic-line-complete-outdated {
  color: red;
}

</style>
